import { publicPathUrl } from '@/utils/common';

/**
 * 将对象添加当作参数拼接到URL上面
 * @param baseUrl 需要拼接的url
 * @param obj 参数对象
 * @returns {string} 拼接后的对象
 * 例子:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==> www.baidu.com?a=3&b=4
 */
export const setObjToUrlParams = (baseUrl: string, obj: object): string => {
  let parameters = '';
  let url = '';
  for (const key in obj) {
    parameters += `${key}=${encodeURIComponent(obj[key])}&`;
  }
  parameters = parameters.replace(/&$/, '');
  if (/\?$/.test(baseUrl)) {
    url = baseUrl + parameters;
  } else {
    url = baseUrl.replace(/\/?$/, '?') + parameters;
  }
  return url;
};

/**
 * 将URL上面的参数转换成对象
 * @param queryStr URL的参数
 * 例子:
 *  let queryStr = 'www.baidu.com?a=3&b=4'
 *  setUrlParamsToObj(queryStr)
 *  ==> {a: '3', b: '4'}
 */
export const setUrlParamsToObj = (queryStr: string): { [x: string]: any } => {
  const [, queryString] = queryStr.split('?');
  return queryString.split('&').reduce((query, item) => {
    const [key, value = ''] = item.split('=');
    query[key] = value;
    return query;
  }, {});
};

/**
 * 检测文件url是否以http开头的完整url，如不是，拼接basePathUrl返回完整路径
 * @param avatar 图片地址
 */
export const getFileHttpUrl = (avatar: string) => {
  if (!avatar) return '';
  if (avatar.startsWith('http') || avatar.startsWith('https')) {
    return avatar;
  }
  return publicPathUrl + avatar;
};

/**
 * 将路径中重复的正斜杆替换成单个斜杆隔开的字符串
 * @param path 要处理的路径
 * @returns {string} 将/去重后的结果
 */
export const uniqueSlash = (path: string) => path.replace(/(https?:\/)|(\/)+/g, '$1$2');
